﻿using System;
using System.Web;
using System.Text;

namespace Doo.Caching
{
    /// <summary>
    /// 用于获取数据版本
    /// </summary>
    public class DataVersionHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string query = context.Request.QueryString["d"];
            if (!string.IsNullOrEmpty(query))
            {
                string[] names = GetNames(query);
                context.Response.Write("var pagever={");
                foreach (string n in names)
                {
                    long v;
                    PageCacheHelper.Versions.TryGetValue(n, out v);
                    context.Response.Write("\""+n + "\":" + v + ",");
                }
                context.Response.Write("\"__global\":" + PageCacheHelper.GlobalVersion + "};");

            }
        }

        #endregion

        public static string url = "/dataver.axd";

        public static string GetUrl(string[] names)
        {
            return url + "?d=" + Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join("\n", names)));
        }

        public static string[] GetNames(string query)
        {
            string source = Encoding.UTF8.GetString(Convert.FromBase64String(query));
            return source.Split('\n');
        }
    }
}
